<template>
  <div class="wrap content">
    <section class="inner-top">
      <span>应用管理</span>
    </section>
    <section class="inner-bottom">
      <el-row :gutter="10">
        <el-col :span="24" align="right" v-if="!disabledCurrentNode">
          <el-button type="primary" icon="el-icon-plus" plain @click="addApp=true">添加应用</el-button>
          <el-button type="primary" icon="el-icon-plus" plain @click="addClassify=true">添加分类</el-button>
        </el-col>
        <el-col :span="5">
          <div class="tree">
            <el-input placeholder="输入关键字进行过滤" v-model="filterText" suffix-icon="el-icon-search"></el-input>
            <el-tree default-expand-all :data="tree" node-key="id" :props="treeProps" :current-node-key="defaultNode.id*1" icon-class="el-icon-arrow-right" :expand-on-click-node="false" :filter-node-method="filterNode" @node-click="nodeClick" ref="tree">
            </el-tree>
          </div>
        </el-col>
        <el-col :span="19">
          <router-view v-if="reloadRouter" @refreshCates="getAllCates" @delCateOrApp="initPageData" :classifyList="filterClassifyTree" :appList="filterClassifyTree"></router-view>
        </el-col>
      </el-row>
      <!-- 内置图标 -->
      <icon :show.sync="showIcon" @changeIcon="changeIcon"></icon>
      <!-- 添加应用 -->
      <el-dialog :visible.sync="addApp" width="750px" @open="getClassTree" @close="clearAddAppFrom('app')">
        <common-title>添加应用</common-title>
        <div class="form_wrap">
          <el-form :model="addAppForm" :rules="appRules" ref="addAppForm" label-width="100px" style="width: 100%">
            <el-form-item label="应用名称" prop="name">
              <el-input v-model.trim="addAppForm.name" placeholder="请输入应用名称"></el-input>
            </el-form-item>
            <el-form-item label="应用code" prop="code">
              <el-input v-model.trim="addAppForm.code" placeholder="请输入应用code"></el-input>
            </el-form-item>
            <el-form-item label="应用地址" prop="url">
              <el-input v-model.trim="addAppForm.url" placeholder="请输入访问地址"></el-input>
            </el-form-item>
            <el-form-item label="应用分类" prop="categoryId">
              <el-cascader ref="parentIdCascader" v-model='addAppForm.categoryId' :options="filterClassifyTree" :props="{ checkStrictly: true, value: 'id', label:'name', children:'children' }" @change="cateParentIdChange" style="width:100%" clearable></el-cascader>
            </el-form-item>
            <el-form-item label="应用描述" prop="description">
              <el-input v-model.trim="addAppForm.description" placeholder="请输入应用描述"></el-input>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="启用 / 禁用" prop="enabled">
                  <el-switch v-model="addAppForm.enabled" active-color="#5978E2" inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="第三方应用" prop="thirdApp">
                  <el-switch v-model="addAppForm.thirdApp" active-color="#5978E2" inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="应用图标：" prop="icon">
              <div class="app_icon_wrap">
                <span>
                  <el-image :src="addAppForm.icon" style="width:50px;line-height:50px;text-align:center;margin-right:20px">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </span>
                <el-upload :action="serverPath" with-credentials :before-upload="beforeUpload" :on-success="successUploadCallback" :show-file-list="false">
                  <span class="btn">上传</span>
                </el-upload>
                <span class="btn" @click="showIcon=true">内置</span>
              </div>
            </el-form-item>
          </el-form>
          <div class="ope">
            <el-button type="primary" @click="addAppFn" :loading="btnLoading">确认</el-button>
          </div>
        </div>
      </el-dialog>
      <!-- 添加分类 -->
      <el-dialog :visible.sync="addClassify" width="605px" @open="getClassTree" @close="clearAddAppFrom('class')">
        <common-title>添加分类</common-title>
        <div class="form_wrap">
          <el-form :model="addCateForm" :rules="cateRules" ref="addCateForm" label-width="100px" style="width: 100%">
            <el-form-item label="分类名称" prop="name" placeholder="请输入分类名">
              <el-input v-model.trim="addCateForm.name"></el-input>
            </el-form-item>
            <el-form-item label="上级分类" prop="parentId">
              <el-cascader ref="cateParentIdCascader" v-model='addCateForm.parentId' :options="filterClassifyTree" :props="{ checkStrictly: true, value: 'id', label:'name', children:'children' }" @change="cateParentIdChange" style="width:100%" placeholder="请选择上级分类"></el-cascader>
            </el-form-item>
            <el-form-item label="分类排序" prop="sort">
              <el-input v-model="addCateForm.sort"></el-input>
            </el-form-item>
            <el-form-item label="是否启用" prop="enabled">
              <el-radio-group v-model="addCateForm.enabled">
                <el-radio label="1">启用</el-radio>
                <el-radio label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div class="ope">
            <el-button type="primary" @click="addCate" :loading="btnLoading">确认</el-button>
          </div>
        </div>
      </el-dialog>
    </section>
  </div>
</template>
<script>
import icon from '../components/icon'
import {prodUrl} from '@/tools/utils'
import uploadServer from '@api/uploadServer'
import {getClassTreePOST, createAppUsingPOST, getCategoryAndAppTree, appcategoryInsertCategory} from '@api/systemManage'
export default {
  components: {icon},
  data () {
    return {
      userList: [],
      reloadRouter: true,
      // 绑定添加应用，分类的级联选择器，用来清空级联
      addAppAdmin: [],
      addAppClass: [],
      addclass: [],
      loading: false,
      btnLoading: false,
      showIcon: false,
      addClassify: false,
      addApp: false,
      filterText: '',
      tree: [],
      treeProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      currentNode: {id: null}, // 当前选中项
      // 添加应用
      addAppForm: {
        code: null,
        name: '',
        url: '',
        categoryId: null, // 分类id
        sort: null,
        enabled: null,
        description: null,
        thirdApp: null, // 是否第三方平台应用
        type: null, // 类型
        // hidden: true,
        active: true,
        // inType: 'CAS',
        appMaintain: 'N',
        // thirdApp: '',
        icon: ''
      },
      // 添加分类
      addCateForm: {
        // crtId: null,
        name: null,
        parentId: null,
        sort: 1,
        enabled: '1'
      },
      // filterAppTree: [], // 用于添加应用，已经过滤应用
      filterClassifyTree: [], // 用于添加分类
      organizationUser: [], // 组织树
      cateRules: {
        name: [
          { required: true, message: '请输入分类名', trigger: 'blur' }
        ]
      },
      appRules: {
        code: [{required: true, message: '请输入应用code', trigger: 'blur'}],
        name: [{required: true, message: '请输入应用名称', trigger: 'blur'}],
        url: [{required: true, message: '请输入访问地址', trigger: 'blur'}],
        categoryId: [{required: true, message: '请选择应用分类', trigger: 'blur'}]
      },
      userSn: 'admin',
      defaultNode: {
        id: null,
        type: null
      },
      serverPath: uploadServer.uploadFile, // 图片上传服务
      accept: ['jpg', 'jpeg', 'png'] // 允许上传的文件格式
    }
  },
  async created () {
    this.initPageData()
  },
  computed: {
    disabledCurrentNode () { // 大厅下面的不能做任何修改 10:大厅（分类）；57：一站式服务大厅（应用）;11:大厅下面的默认分类
      return Number(this.currentNode.id) === 10 || Number(this.currentNode.id) === 57 || Number(this.currentNode.id) === 11
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    },
    addApp (n, o) {
      // if (n) this.addAppFromInit()
    },
    addClassify (n, o) {
      // if (n) this.addCateFormInit()
    }
  },
  methods: {
    prodUrl,
    async initPageData () {
      this.getClassTree()
      await this.getAllCates()
      this.gotoFirst()
    },
    // 获取树(左侧分类应用树)
    async getAllCates () {
      await getCategoryAndAppTree().then(res => {
        let tree = res.data
        if (!this.defaultNode.id) {
          this.defaultNode.id = res.data[0].children ? res.data[0].children[0].id : null
          this.defaultNode.type = res.data[0].children ? res.data[0].children[0].type : null // 0-分类 1-应用
        }
        this.tree = JSON.parse(JSON.stringify(tree))
        // this.getClassifyList(tree)
      }).catch(error => {
        console.log(error)
        this.tree = []
        // this.getClassifyList([])
      })
    },
    // 树形过滤方法
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 点击树，传递树节点Id
    nodeClick (data, node) {
      console.log(data)
      this.currentNode = data
      let params = {id: data.id}
      if (Number(data.type) === 0) { // 分类
        this.$router.push({ name: 'classify', query: params })
      } else if (Number(data.type) === 1) { // 应用
        this.$router.push({ name: 'app', query: params })
      }
    },
    // 通过全部分类下第一个id获取分类，应用详情
    gotoFirst () {
      // 默认跳转第一个分类或应用
      if (!this.defaultNode.id) return
      let params = {id: this.defaultNode.id}
      if (this.defaultNode.type === 0) {
        this.$router.push({name: 'classify', query: params})
      } else {
        this.$router.push({name: 'app', query: params})
      }
    },
    // 选择内置图标
    changeIcon (src) {
      this.addAppForm.icon = src
      console.log(src)
    },
    // 获取分类树（只包含分类）
    getClassTree () {
      getClassTreePOST().then(res => {
        if (res.status) {
          this.filterClassifyTree = res.data
        }
      })
    },
    //
    cateParentIdChange (val) {
      this.addCateForm.parentId = val[val.length - 1]
      this.addAppForm.categoryId = val[val.length - 1]
    },
    // 添加分类
    addCate () {
      this.$refs.addCateForm.validate((valid) => {
        if (valid) {
          //  let params = Object.assign({}, this.addCateForm)
          let params = {
            'enabled': Boolean(Number(this.addCateForm.enabled)),
            'name': this.addCateForm.name,
            'parentId': this.addCateForm.parentId,
            'sort': this.addCateForm.sort
          }
          if (!params.parentId) {
            params.parentId = -1 // this.filterClassifyTree[0].id ? this.filterClassifyTree[0].id : -1
          }
          if (this.btnLoading) {
            return false
          }
          this.btnLoading = true
          appcategoryInsertCategory(params).then(res => {
            this.addClassify = false
            this.getAllCates()
          }).finally(() => {
            this.btnLoading = false
          })
        }
      })
    },
    // 添加应用
    addAppFn () {
      this.$refs['addAppForm'].validate(valid => {
        if (valid) {
          let params = {
            'categoryId': this.addAppForm.categoryId,
            'description': this.addAppForm.description,
            'code': this.addAppForm.code,
            'enabled': true,
            'icon': this.addAppForm.icon,
            'name': this.addAppForm.name,
            'sort': 1, // this.addAppForm.sort,
            'thirdApp': this.addAppForm.thirdApp,
            // 'type': this.addAppForm.type,
            'url': this.addAppForm.url
            // "code": "string",
            // "createTime": "2019-11-05T09:40:19.391Z",
            // "creator": "string",
            // "deleted": "string",
            // "id": 0,
            // "modifier": "string",
            // "modifyTime": "2019-11-05T09:40:19.391Z",
            // "version": 0
          }
          createAppUsingPOST(params).then(res => {
            if (res.status) {
              this.$message.success('添加应用成功')
              this.addApp = false
              this.getAllCates()
            }
          })
        }
      })
    },
    // 添加应用，上传图标前
    beforeUpload (file) {
      const oversize = file.size / 1024 / 1024 < 1
      let isCorrectFormat = false
      this.accept.map(item => {
        if (file.name.indexOf(`.${item}`) !== -1) isCorrectFormat = true
      })
      if (!oversize) {
        this.$message.error('单个文件大小不能超过 1MB')
      }
      if (!isCorrectFormat) {
        this.$message.error(`仅支持${this.accept.join('、')}格式的文件`)
      }
      return oversize && isCorrectFormat
    },
    // 添加应用，上传图标成功回调
    successUploadCallback (res) {
      if (res.success) {
        this.addAppForm.icon = `${uploadServer.downloadImg}?filePath=${res.filePath}` // 'fastdfs/fileObject/download/image?filePath=' + encodeURIComponent(res.filePath)
      }
    },
    // 重新加载路由
    reload () {
      this.reloadRouter = false
      this.$nextTick(() => {
        this.reloadRouter = true
      })
    },
    clearAddAppFrom (type) {
      if (type === 'app') {
        this.$refs['addAppForm'].clearValidate()
        this.$refs['addAppForm'].resetFields()
        return
      }
      this.$refs['addCateForm'].clearValidate()
      this.$refs['addCateForm'].resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
@import "../../../../../assets/variate.less";
/deep/.el-dialog {
  .br(0.08rem);
  .el-dialog__header {
    padding: 15px;
  }
  .el-dialog__body {
    padding-top: 0.16rem;
  }
}

// 添加应用
.form_wrap {
  padding: 20px 10px;
  box-sizing: border-box;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .form_item {
    display: flex;
    line-height: 36px;
    margin-bottom: 20px;
    width: 100%;
    /deep/.el-radio {
      margin-right: 10px;
    }
    .label {
      display: inline-block;
      color: #666666;
      font-size: 14px;
      margin-right: 10px;
      width: 70px;
    }
    /deep/.el-input,
    /deep/.el-select,
    .app_icon_wrap,
    /deep/.el-slider {
      flex: 1;
    }
    .switch_group {
      justify-content: space-between;
      .label {
        margin: 0;
      }
    }
  }
  .app_icon_wrap {
    display: flex;
    align-items: center;
    .app_icon {
      width: 50px;
      height: 50px;
      line-height: 50px;
      text-align: center;
      margin-right: 26px;
      border-radius: 50%;
      background: #ff9ca9;
      cursor: pointer;
      box-shadow: 0 0 0 6px rgba(255, 156, 169, 0.2);
      i {
        vertical-align: middle;
        font-size: 24px;
        color: #fff;
      }
    }
    .btn {
      display: inline-block;
      border: 1px solid #815df0;
      margin-right: 15px;
      .btn(#fff, #815df0, 22px, 4px);
    }
  }
  .ope {
    display: flex;
    width: 100%;
    justify-content: flex-end;
    .cancel {
      border: 1px solid #5978e2;
      .btn(#fff, #5978e2, 0.36rem);
    }
    .confirm {
      margin-left: 20px;
      .btn(#5978e2, #fff, 0.36rem);
    }
  }
}
.wrap {
  box-sizing: border-box;
  .br(0.08rem);
  // background: #fff;
  display: flex;
  flex-direction: column;
}
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 74px;
  padding: 0 32px;
  box-sizing: border-box;
  border-bottom: 1px solid #dfdfdf;
  .ope {
    display: flex;
    align-items: center;
  }
}
.content {
  display: flex;
  flex: 1;
}
.tree {
  // min-height: 750px;
  overflow: auto;
  min-width: 3.05rem;
  box-sizing: border-box;
  padding: 0 0.3rem;
  border-right: 1px solid #dfdfdf;
  /deep/.el-input {
    margin: 0.3rem 0;
    .el-input__inner {
      height: 36px;
      line-height: 36px;
      border-radius: 36px;
    }
  }
  /deep/.el-tree {
    overflow: auto;
    .active() {
      background: #829ae9;
      color: #fff;
      .br(0.04rem);
    }
    .el-tree-node__expand-icon.is-leaf {
      color: transparent !important;
    }
    .is-current > .el-tree-node__content {
      .active();
      .el-tree-node__expand-icon {
        color: #fff;
      }
    }
    & > .is-current > .el-tree-node__content {
      background: #fff;
      color: #606266;
      .el-tree-node__expand-icon {
        color: #c0c4cc;
      }
    }
    .el-tree-node__content {
      height: 40px;
      &:hover {
        .active();
        .el-tree-node__expand-icon {
          color: #fff;
        }
      }
    }
    & > .el-tree-node > .el-tree-node__content:hover {
      cursor: no-drop;
      background: #fff;
      color: #606266;
      .el-tree-node__expand-icon {
        color: #c0c4cc;
      }
    }
  }
}
</style>
